package com.shen.langchain4j.controller;

import dev.langchain4j.data.message.ImageContent;
import dev.langchain4j.data.message.TextContent;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Base64;

/**
 * 调用大模型控制层接口类
 */
@Slf4j
@RestController
@RequestMapping(value = "/image")
public class ImageModelController {
    @Autowired
    private ChatModel chatModel;
    @Value("classpath:static/image/TencentQuarterlyReport.png")
    private Resource resource;

    /**
     * 多模态调用，采用文本加图片的形式进行图片理解
     *
     * @return 图片理解内容
     * @throws IOException IO异常
     */
    @GetMapping("/readImage")
    public String readImageContent() throws IOException {
        String modelResult = null;
        //图片转码，通过Base64编码将图片转换为字符串
        byte[] byteArray = resource.getContentAsByteArray();
        String base64Str = Base64.getEncoder().encodeToString(byteArray);

        //多模块提示词，既包含文本也包含图片，同时发送给大模型进行处理
        UserMessage userMessage = UserMessage.from(
                TextContent.from("从下面图片中分析图片中内容，提炼出中心主旨"),
                ImageContent.from(base64Str, "image/png")
        );

        //API调用
        ChatResponse chatResponse = chatModel.chat(userMessage);

        //解析响应体，从ChatResponse中获取AI大模型的回复
        modelResult = chatResponse.aiMessage().text();
        log.info("大模型返回结果为: {}", modelResult);
        return modelResult;
    }
}
